<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>省市二级联动</title>
</head>
<body>

<div id="selectDiv">
    <select name="province" onclick="checkProvice(this)">
        <option value="0">--选择省份--</option>
        <option value="北京">北京</option>
        <option value="河北">河北</option>
        <option value="河南">河南</option>
        <option value="山西">山西</option>
    </select>

    <select name="city">
        <option value="0">--请选择城市--</option>
    </select>
</div>
</body>
<script>
    //1.给省份准备城市数据
    var data = {
        "北京":["海淀区","西城区","东城区","延庆区","门头沟区","石景山区","朝阳区","通州区"],
        "河北":["石家庄","张家口","邯郸","保定","唐山","邢台"],
        "河南":["郑州","洛阳","开封","安阳","鹤壁","濮阳","新乡","焦作"],
        "山西":["太原","大同","朔州","忻州","阳泉","吕梁","晋中"]
    }

    function checkProvice(thisObj){
        //2.获取省份选择框的值
        var pro = thisObj.value
        // 3. 根据省份获取data中对应的城市
        var arrCity = data[pro]




        // 5. 将对应的城市添加到 城市 select中
        var cityObj = document.getElementsByName("city")[0]
        //4. 清空上一次的选择
        cityObj.innerHTML = ""

        // arrCity是一个数组，需要创建对应的option 添加到 select 中
        if(arrCity!=null){
            for(var i = 0;i<arrCity.length;i++){
            //创建元素  option
            var oObj = document.createElement("option")
            // 给option赋值
            oObj.innerHTML = arrCity[i]
            // 将option元素添加select
            cityObj.appendChild(oObj)
        }
        }
    }
</script>
</html>